<template>
  <ele-modal :width="400" :body-style="{ height: '450px', overflow: 'scroll' }" title="配置菜单" position="center"
    v-model="visible" @open="handelOpen" @close="handelClose">
    <el-tree ref="treeRef" style="max-width: 400px" :data="menuTree" show-checkbox node-key="id" highlight-current
      :props="{ label: 'name' }" @check-change="nodeClick" />
    <template #footer>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </ele-modal>
</template>

<script setup lang="ts">
import { ref } from "vue"
import { EleMessage } from "ele-admin-plus";
import type { TreeInstance } from 'element-plus';
import { queryAllTree } from "@/api/system/SysMenu";
import { queryList, edit } from "@/api/system/SysModuleMenu"
import type { SysMenu } from "@/api/system/SysMenu/model";
import type { SysModule } from "@/api/system/SysModule/model";

const props = defineProps<{
  module: SysModule | null
}>()

const visible = defineModel({ type: Boolean });
const treeRef = ref<TreeInstance | null>(null)
const menuTree = ref<SysMenu[]>([])
const selections = ref<string[]>([])

const save = async () => {
  const res = await edit({ moduleId: props.module!.id, menuIdList: selections.value })
  if (res.code == 200) {
    EleMessage.success('保存成功')
    visible.value = false
  } else {
    EleMessage.error('保存失败')
  }
}

const nodeClick = () => {
  selections.value = treeRef.value!.getCheckedNodes(false, true).map(e => e.id)
}

const handelOpen = async () => {
  const menuRes = await queryAllTree()
  menuTree.value = menuRes.data!
  const res = await queryList(props.module!.id)
  treeRef.value?.setCheckedKeys(res.data!)
}

const handelClose = () => {
  selections.value = []
}

</script>

<style scoped></style>
